<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/26
 * Time: 11:36
 */

namespace app\api\controller;


use app\api\service\Address;
use app\api\service\Goods;
use app\common\Code;
use app\common\model\UserFund;
use app\common\Session;
use think\Db;


class V2
{
    const CART_DATA = "CART_DATA";

    /**
     * 购物车前往下单
     * cart_id   选择的购物车数据的id
     * @param array $cart_id
     */
    public function cart_to_order($cart_id = [])
    {
        $user = Session::get_local_user();
        if (empty($user)) {
            response_json(Code::NO_LOGIN);
        }
        /** @var \app\common\model\UserCart $cart */
        $cart = new \app\common\model\UserCart();
        $cart_list = [];
        foreach ($cart_id as $item) {
            if (!isset($cart_list[$item])) {
                $item_data = $cart->get(["id" => $item]);
                if (!empty($item_data)) {
                    $item_data->good = Goods::good(['shop_goods.id' => $item_data->goods_id]); //商品保存
                    if (!empty($item_data->good)) {
                        $cart_list[$item] = $item_data; // 有商品就push
                    }
                }
            }
        }
        session(self::CART_DATA, $cart_list);
        response_json(Code::NONE);
    }

    /**
     * 前往生成订单页面所需要的数据
     */
    public function create_order()
    {
        $param = input();
        $user = Session::get_local_user();
        if (empty($user)) {//请登录
            response_json(Code::NO_LOGIN);
        }
        $cart_goods = session(self::CART_DATA);
        if (!is_array($cart_goods)) {//购物车为空
            response_json(Code::EMPTY_CART);
        }
        /**
         * 生成地址供选择
         */
        $add_cond = [];
        $add_cond["user_id"] = $user->id;
        if (isset($param["community_id"])) {
            $add_cond["community_id"] = $param["community_id"];
        }
        $address_data = Address::list_($add_cond); // 用户地址

        ##判断用户余额 能否继续下单
        $payment = new UserFund();
        $member_money = $payment->get(["user_id" => $user->id]);
        if (isset($member_money->value) && $member_money->value < 0) {
            response_json(Code::YU_E_BUZU); // 余额不足
        }

        /**
         * 集体给前段页面传值
         */
        response_json(Code::NONE,
            [
                "goods" => $cart_goods,
                "address" => $address_data
            ]);
    }

    /**
     * 下单
     * @param null $address_id
     * @param int $ziti_type
     * @param int $community_id
     * @param string $memo
     * @return \think\response\Jsonp
     */
    public function  create_order_data(
        $address_id = null,
        $ziti_type = 0, //自提0 配送是1
        $community_id = 0,
        $memo = ""
    )
    {
        $param = input();
        /** @var \app\common\model\Users $user */
        $user = Session::get_local_user();
        if (empty($user)) {//请登录
            response_json(Code::NO_LOGIN);
        }
        $cart_goods = session(self::CART_DATA);
        if (!is_array($cart_goods)) {//购物车为空  #####
            response_json(Code::EMPTY_CART);
        }
        $address = Address::address($address_id);
        if (empty($address)) {
            response_json(Code::ADDRESS_ERROR);
        }
        ##商品分类
        $r_data = $this->goods_hand($cart_goods);
        // 启动事务
        /**
         * 交易号  默认交易金额
         */
        $code = "shop" . date("YmdHi") . substr(md5(mt_rand() + time()), 0, 16);
        $fee = 0;
        /**
         * 创建订单
         */
        do {
            $order_list = [];
            foreach ($r_data as $k => $v) {
                $seller_id = $k;
                $goods_data = $v;
                $m_order = new \app\common\model\Order();
                $order_list[] = $m_order->create_order(
                    $community_id,
                    $seller_id,
                    $user,
                    $address,
                    $goods_data,
                    $ziti_type,
                    $memo
                );
            }
        } while (0);
        /**
         * 创建交易
         */
        do {
            foreach ($order_list as $order) {
                #计算总的金额
                $fee += isset($order->total) ? $order->total : 0;
                \app\common\model\TradeOrder::create_relation($code, $order->order_id);
            }
            \app\common\model\Trade::create_shop($code, $fee, "创建一笔购物交易 ");
        } while (0);
        response_json(Code::NONE,
            [
                "code" => $code,
                "fee" => $fee
            ]
        );
    }

    /**
     * <span style="color:#ccc;">预处理商品  给商品分类  [不是app接口]</span>
     * @param $goods
     * @return array
     */

    private function goods_hand($goods)
    {
        $r_data = [];
        /**
         * 对商品分类
         * 创建订单商品数据
         */
        do {
            $m_goods = new \app\common\model\Goods();

            foreach ($goods as $v) {
                $goods_id = $v['goods_id'];
                $count = $v['count'];
                /** @var \app\common\model\Goods $good */
                $good = $m_goods->fetch_by_id($goods_id);
                if (empty($good)) {
                    #商品已下架
                    response_json(Code::GOODS_NOT_EXISTS);
                }
                /** 统计销量 */
                $good->increase_sale($count);
                /** 减少库存  */
                $good->dec_stock($count);
                $seller_id = $good->seller_id;
                if (!isset($r_data[$seller_id])) {
                    $r_data[$seller_id] = [];
                }
                $r_data[$seller_id][] = [
                    "goods" => $good,
                    "count" => $count,
                ];
            }
        } while (0);
        return $r_data;
    }

    /**
     * 充值
     * 参数
     * fee  充值的金额
     * memo 备注
     *
     * @param int $fee
     * @param string $memo
     */
    function recharge($fee = 0, $memo = '')
    {
        $user = Session::get_local_user();
        if (empty($user)) {//请登录
            response_json(Code::NO_LOGIN);
        }
        $code = sprintf(
            "%s%s%s",
            "recharge",
            time(),
            rand(1000, 9999)
        );
        /**
         * 创建交易
         */
        \app\common\model\Trade::create_recharge($code, $fee, "创建一笔充值交易");
        response_json(Code::NONE, [
            "code" => $code,
            "fee" => $fee,
        ]);
    }

}